package oot.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import oot.data.Config;
import oot.data.Connection;
import oot.data.DoWithServer;
import oot.data.JSonPaser;
import oot.data.Tweet;
import oot.data.User;
import oot.tab.activity.R;
import oot.view.HeadTab;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ott.adapter.TweetAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.util.Linkify;
import android.text.util.Linkify.TransformFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class SingleTweetActivity extends Activity {
	private LinearLayout inReplyLayout;
	private LinearLayout replyLayout;
	private TextView tvUserID;
	private TextView tvExtrarInfo;

	private ArrayList<Tweet> listInReply;
	private ArrayList<Tweet> listReply;
	private ArrayList<User> listUser;

	private Button btReply;
	private Button btDelede;
	private CheckBox cbRetweet;
	private CheckBox cbFavorite;
	private TextView tvUserScreenName;
	private TextView tvContentTweet;
	private Tweet mTweet;
	private Context mContext;
	private LinearLayout retweets;
	private LinearLayout favorites;
	private LinearLayout both;
	private ScrollView scrollView;
	private LinearLayout fillScrollLayout;
	private TextView tvInReplyTo;
	private String tempTweetContent;
	private ImageView userAvatar;

	private JSONObject js;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.tweet_single_layout);
		// for all activity
		HeadTab head = new HeadTab(this);
		head.createHeadTabAction("Tweet");
		mTweet = (Tweet) (getIntent().getSerializableExtra("TWEET"));
		if(mTweet.getType().equals(Tweet.TYPE_RETWEET)){
			mTweet.setTweetId(mTweet.getRetweet().getTweetId());
		}
		// Log.i("test", "content: " + mTweet.getContent());
		// Log.i("test", "username: " + mTweet.getUser().getUserName());
		scrollView = (ScrollView) findViewById(R.id.scv_main);
		fillScrollLayout = (LinearLayout) findViewById(R.id.lo_fill_scroll);
		final DoWithServer doWithServer = new DoWithServer(mContext);
		LinearLayout la = (LinearLayout) findViewById(R.id.lo_single_tweet_delete);
		inReplyLayout = (LinearLayout) findViewById(R.id.lo_inreply);
		replyLayout = (LinearLayout) findViewById(R.id.lo_replies);
		tvUserID = (TextView) findViewById(R.id.tv_user_id);
		tvUserScreenName = (TextView) findViewById(R.id.tv_user_screen_name);
		tvExtrarInfo = (TextView) findViewById(R.id.tv_extra_info);
		// imgTweetUserAvata = (ImageView) findViewById(R.id.img_tweet_avata);
		tvContentTweet = (TextView) findViewById(R.id.tv_tweet_content);
		btReply = (Button) findViewById(R.id.bt_tweet_single_reply);
		cbRetweet = (CheckBox) findViewById(R.id.cb_tweet_single_retweet);
		btDelede = (Button) findViewById(R.id.bt_tweet_single_delete);
		cbFavorite = (CheckBox) findViewById(R.id.cb_tweet_single_favorite);
		retweets = (LinearLayout) findViewById(R.id.lo_s_retweet);
		favorites = (LinearLayout) findViewById(R.id.lo_s_favorite);
		both = (LinearLayout) findViewById(R.id.lo_s_both);
		// imgContent =
		// (ImageView)findViewById(R.id.img_tweet_single_image_content);

		inReplyLayout.setVisibility(View.GONE);
		replyLayout.setVisibility(View.GONE);
		fillScrollLayout.getLayoutParams().height = 0;
		getInReply(mTweet);
		getReply(mTweet);
		getListUser(mTweet);
		// if()
		String exInfo = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
		try {
			Date tempDate = sdf.parse(mTweet.getCreatedDate());
			// tempDate.
			SimpleDateFormat sdf2 = new SimpleDateFormat(
					"hh:mm aaa dd MMM yyyy");
			exInfo = sdf2.format(tempDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (mTweet.getType().equals(Tweet.TYPE_RETWEET))
			exInfo = exInfo.concat("\n Retweeted by @"
					+ mTweet.getUser().getUserName());
		tvExtrarInfo.setText(exInfo);
		userAvatar = (ImageView)findViewById(R.id.img_tweet_avata);
		userAvatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
				i.putExtra("user", mTweet.getUser());
				startActivity(i);
			}
		});
		AQuery avatar = new AQuery(SingleTweetActivity.this);
		avatar.id(R.id.img_tweet_avata)
				.visible()
				.image(Connection.BASE_URL_IMAGE
						+ mTweet.getUser().getUserAvatarURL(), true, true, 0,
						R.drawable.m05_item_avar);
		
		

		// if tweet is retweet
		if (mTweet.getRetweet() == null) {
			tvUserID.setText(mTweet.getUser().getUserName());
			tvUserScreenName.setText(mTweet.getUser().getUserScreenName());
			tvContentTweet.setText(mTweet.getContent());

		} else {
			tvUserID.setText(mTweet.getRetweet().getUser().getUserName());
			tvUserScreenName.setText(mTweet.getRetweet().getUser()
					.getUserScreenName());
			tvContentTweet.setText(mTweet.getRetweet().getContent());
		}
		if (mTweet.getFavorite().equals(Tweet.FAVORITE)) {
			cbFavorite.setChecked(true);
		}
		if (mTweet.getReTweetedByMe().equals(Tweet.RETWEETED_IS_BY_ME)) {
			cbRetweet.setChecked(true);
		}
		// tweet of user
		if (mTweet.getUser().getUserID()
				.equals(FlashScreenActivity.user.getUserID())) {
			cbRetweet.setClickable(false);
			la.setVisibility(View.VISIBLE);
		} else { // tweet of other user
			cbRetweet.setClickable(true);
			la.setVisibility(View.GONE);
		}

		// resolve content tweet
		if (mTweet.getImgURL().length() > 0) {
			Log.i("test", "" + mTweet.getImgURL());
			AQuery aq = new AQuery(this);
			aq.id(R.id.img_tweet_single_image_content)
					.visible()
					.image(Connection.BASE_URL_IMAGE+mTweet.getImgURL(),
							true,
							true,
							getWindowManager().getDefaultDisplay().getWidth() * 8 / 10,
							R.drawable.image_album);
		}

		btReply.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// get
				Tweet tempT = new Tweet();
				tempT.setParentTweetId(mTweet.getTweetId());
				tempT.setType(Tweet.TYPE_REPLY);
				if (mTweet.getType().equals(Tweet.TYPE_RETWEET))
					tempT.setParentTweetId(mTweet.getRetweet().getTweetId());
				if (!tempTweetContent.contains("@"
						+ mTweet.getUser().getUserName()))
					tempTweetContent = tempTweetContent.concat("@"
							+ mTweet.getUser().getUserName());
				tempT.setContent(tempTweetContent);
				Intent i = new Intent(mContext, TweetActivity.class);
				i.putExtra(Config.TEMP_TWEET, tempT);
				startActivity(i);
			}
		});
		if (mTweet.getUser().getUserID()
				.equals(FlashScreenActivity.user.getUserID())) {
			Log.e("test", "clicked true");
			LinearLayout l = (LinearLayout) findViewById(R.id.lo_tweet_single_retweet);
			l.setVisibility(View.GONE);
		}
		Log.e("test", "test clicked " + cbRetweet.isClickable());
		cbRetweet.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.i("test", "clicked");
				if (cbRetweet.isChecked()) {

					AlertDialog.Builder builder = new AlertDialog.Builder(
							mContext);
					builder.setNeutralButton("other",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

								}
							});
					builder.setMessage("Retweet this?")
							.setCancelable(false)
							.setPositiveButton("Yes",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											doWithServer
													.doRetweet(mTweet, true);
											finish();
										}
									})
							.setNegativeButton("No",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											cbRetweet.setChecked(false);
											dialog.cancel();
											return;
										}
									});
					AlertDialog alert = builder.create();
					alert.show();
				} else {
					doWithServer.doRetweet(mTweet, false);
				}
			}
		});
		cbFavorite.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {

					doWithServer.doFavorite(mTweet, true);
				} else {

					doWithServer.doFavorite(mTweet, false);
				}
			}
		});
		btDelede.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setMessage("Delete this?")
						.setCancelable(false)
						.setPositiveButton("Yes",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										doWithServer.doDelete(mTweet);
										finish();
									}
								})
						.setNegativeButton("No",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();

			}
		});

		retweets.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "Reweet click",
						Toast.LENGTH_LONG).show();
				Intent intent = new Intent(getApplicationContext(),
						ListRetweetsActivity.class);
				intent.putExtra("tweet", mTweet);
				startActivity(intent);
			}
		});

		favorites.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "Favorites click",
						Toast.LENGTH_LONG).show();
				Intent intent = new Intent(getApplicationContext(),
						ListFavoritesActivity.class);
				intent.putExtra("tweet", mTweet);
				startActivity(intent);
			}
		});
		getCount(mTweet);
	}

	private void getCount(Tweet t) {
		RequestParams requestParams = new RequestParams();
		requestParams.put("tweet_id", t.getTweetId());
		Connection.post("tweets/get_retweet_count", requestParams,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String res) {
						super.onSuccess(res);

						paserReTweetCount(res);
					}
				});

		RequestParams params = new RequestParams();
		params.put("tweetid", t.getTweetId());
		params.put("get_userid", t.getUser().getUserID());
		Connection.post("favorites/favorite_count", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String res) {
						// TODO Auto-generated method stub
						super.onSuccess(res);
						paserFavoriteCount(res);
					}
				});

	}

	private void paserReTweetCount(String res) {
		Log.e("RESRE", res);
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(res);

			if (jsonObject.getInt("status_code") == 0) {
				int rtc = jsonObject.getInt("entity");
				if (rtc > 0) {
					retweets.setVisibility(View.VISIBLE);
					TextView t = (TextView) findViewById(R.id.tv_s_retweetcount);
					t.setText("" + rtc);
					both.setVisibility(View.VISIBLE);
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void paserFavoriteCount(String res) {
		Log.e("RESFA", res);
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(res);

			if (jsonObject.getInt("status_code") == 0) {
				int fvc = jsonObject.getInt("entity");
				if (fvc > 0) {
					favorites.setVisibility(View.VISIBLE);
					TextView t = (TextView) findViewById(R.id.tv_s_favoritecount);
					t.setText("" + fvc);
					both.setVisibility(View.VISIBLE);
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void getReply(Tweet t) {
		String api = "/Tweets/get_replies";
		RequestParams params = new RequestParams();
		params.put("tweet_id", t.getTweetId());

		Log.i("test", params.toString());
		// Connection.setBaseURL("http://192.168.1.9");
		Connection.post(api, params, new AsyncHttpResponseHandler() {
			public void onSuccess(String arg0) {
				Log.i("test", "return --------" + arg0);
				super.onSuccess(arg0);
				try {
					js = new JSONObject(arg0);
					if (js.getInt("status_code") != 0) {
						// show error message if error occur

						Toast toast = Toast.makeText(mContext,
								js.getString("message"), Toast.LENGTH_SHORT);
						toast.show();
					} else {
						JSONArray jsTweets = (JSONArray) js.get("entity");
						listReply = new ArrayList<Tweet>();
						for (int i = 0; i < jsTweets.length(); i++) {
							// add to list tweet
							listReply.add(JSonPaser
									.paserTweet((JSONObject) jsTweets.get(i)));

							// finish();
						}
						TweetAdapter adapterReply = new TweetAdapter(mContext,
								listReply);
						// lvReply.setAdapter(adapterReply);
						for (int i = 0; i < listReply.size(); i++) {
							replyLayout.addView(adapterReply.getView(i, null,
									null));
						}
						if (listReply.size() > 0)
							replyLayout.setVisibility(View.VISIBLE);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}

	private void getInReply(Tweet t) {
		String api = "/Tweets/get_parent_of_replytweet";
		RequestParams params = new RequestParams();
		params.put("tweet_id", t.getTweetId());

		Log.i("test", params.toString());
		// Connection.setBaseURL("http://192.168.1.9");
		Connection.post(api, params, new AsyncHttpResponseHandler() {
			public void onSuccess(String arg0) {
				Log.i("test", "return --------" + arg0);
				super.onSuccess(arg0);
				try {
					js = new JSONObject(arg0);
					if (js.getInt("status_code") != 0) {
						// show error message if error occur

						Toast toast = Toast.makeText(mContext,
								js.getString("message"), Toast.LENGTH_SHORT);
						toast.show();
					} else {
						JSONArray jsTweets = (JSONArray) js.get("entity");
						listInReply = new ArrayList<Tweet>();
						for (int i = 0; i < jsTweets.length(); i++) {
							// add to list tweet

							listInReply.add(JSonPaser
									.paserTweet((JSONObject) jsTweets.get(i)));
						}
						TweetAdapter adapterInReply = new TweetAdapter(
								mContext, listInReply);

						for (int i = 0; i < listInReply.size(); i++) {

							inReplyLayout.addView(
									adapterInReply.getView(i, null, null), 0);
						}
						if (listInReply.size() > 0)
							inReplyLayout.setVisibility(View.VISIBLE);
						tvInReplyTo = (TextView) findViewById(R.id.tv_in_reply_to);
						LayoutParams params = new LayoutParams(20, tvInReplyTo
								.getTop());

						params.height = 200;
						fillScrollLayout.setLayoutParams(params);
						// /params.height = ;
						scrollView.post(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								scrollView.scrollTo(0, tvInReplyTo.getTop());
								Log.i("test", "" + tvInReplyTo.getTop() + "   "
										+ fillScrollLayout.getHeight());
							}
						});

					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}

	private void getListUser(Tweet t) {
		String api = "/mentions/list_mention";
		RequestParams params = new RequestParams();
		params.put("tweet_id", t.getTweetId());

		Log.i("test", params.toString());
		// Connection.setBaseURL("http://192.168.1.9");
		Connection.post(api, params, new AsyncHttpResponseHandler() {
			public void onSuccess(String arg0) {
				Log.i("test", "return list --------" + arg0);
				super.onSuccess(arg0);
				try {
					js = new JSONObject(arg0);
					if (js.getInt("status_code") != 0) {
						// show error message if error occur

						Toast toast = Toast.makeText(mContext,
								js.getString("message"), Toast.LENGTH_SHORT);
						toast.show();
					} else {
						final JSONArray jsUsers = (JSONArray) js.get("entity");
						listUser = new ArrayList<User>();
						StringBuilder pattern = new StringBuilder();
						pattern.append("(");
						for (int i = 0; i < jsUsers.length(); i++) {
							// add to list tweet
							// Log.i("test",""+jsUsers.get(i).toString());
							pattern.append("@");
							listUser.add(JSonPaser
									.paserUser(((JSONObject) jsUsers.get(i))
											.getJSONObject("User")));

							pattern.append(JSonPaser.paserUser(
									((JSONObject) jsUsers.get(i))
											.getJSONObject("User"))
									.getUserName());
							pattern.append("|");
						}
						// remove | at end of string
						if (pattern.length() > 0)
							pattern.deleteCharAt(pattern.length() - 1);
						pattern.append(")");
						tempTweetContent = "";
						if (listUser.size() > 0) {
							tempTweetContent = pattern.substring(1,
									pattern.length() - 1);

						}
						tempTweetContent = tempTweetContent.replace("|", " ");
						TransformFilter myTransformFilter = new TransformFilter() {
							@Override
							public String transformUrl(Matcher match, String url) {
								String tempURL = url.substring(1);
								for (int i = 0; i < listUser.size(); i++) {
									if (tempURL.equals(listUser.get(i)
											.getUserName()))
										try {
											return jsUsers.get(i).toString();
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
								}
								return url.substring(1); // remove the $ sign
							}
						};
						Pattern userMatcher;
						if (jsUsers.length() > 0) {
							userMatcher = Pattern.compile(pattern.toString());
							String scheme = "twitter.userprofile://";
							// Linkify.addLinks(tvContentTweet, userMatcher,
							// scheme);
							Linkify.addLinks(tvContentTweet, userMatcher,
									scheme, null, myTransformFilter);
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}
}
